package com.ctvit.cch.core.task;

import com.ctvit.cch.ai.pojo.dto.GenerateCreationDTO;
import com.ctvit.cch.ai.pojo.vo.GenerateCreationVO;
import com.ctvit.cch.ai.service.ILlmService;
import com.ctvit.cch.core.enums.GenerateStatusEnum;
import com.ctvit.cch.core.pojo.domain.InspirationRecord;
import com.ctvit.cch.core.pojo.vo.creative.InspirationCreationListVO;
import com.ctvit.cch.core.service.IInspirationCreationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
 * 灵感创作任务
 *
 * @author heyingcheng
 * @date 2025/10/27
 */
@Slf4j
@Component("inspirationCreationTask")
@ConditionalOnProperty(name = "cch.core.task.inspiration-creation.enabled", havingValue = "true")
public class InspirationCreationTask implements SchedulingConfigurer {

    private static final String CRON_EXPRESSION = "0/5 * * * * ?";

    @Resource
    private IInspirationCreationService inspirationCreationService;

    @Resource
    private ILlmService llmService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(this::execute, triggerContext -> {
            CronTrigger trigger = new CronTrigger(CRON_EXPRESSION);
            return trigger.nextExecution(triggerContext);
        });
    }

    public void execute() {
        log.debug("执行灵感创作任务-开始");

        List<InspirationCreationListVO> inspirationCreationList = inspirationCreationService.listByStatus(GenerateStatusEnum.QUEUED.name());
        for (InspirationCreationListVO vo : inspirationCreationList) {
            generateCreation(vo);
        }

        log.debug("执行灵感创作任务-结束");
    }

    private void generateCreation(InspirationCreationListVO vo) {
        String creationId = vo.getCreationId();
        try {
            inspirationCreationService.updateStatus(creationId, GenerateStatusEnum.QUEUED.name(), GenerateStatusEnum.ING.name());
            List<GenerateCreationVO> creations = llmService.generateCreation(new GenerateCreationDTO(vo.getTitle(), vo.getDescription()));

            int size = creations.size();
            List<InspirationRecord> records = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                GenerateCreationVO creationVo = creations.get(i);

                InspirationRecord record = new InspirationRecord();
                record.setCreationId(creationId);
                record.setTitle(creationVo.getTitle());
                record.setKeywords(ObjectUtils.defaultIfNull(creationVo.getKeywords(), Collections.emptyList()));
                record.setContent(creationVo.getDirection());
                record.setAngle(StringUtils.defaultString(creationVo.getAngle()));
                record.setRecordIndex(i);
                records.add(record);
            }

            inspirationCreationService.updateStatus(vo.getCreationId(), GenerateStatusEnum.SUCCESS.name(), records);
        } catch (Exception e) {
            log.error("执行灵感创作任务异常, creationId:[{}]", creationId, e);
            inspirationCreationService.updateStatus(creationId, GenerateStatusEnum.ING.name(), GenerateStatusEnum.FAILURE.name());
        }
    }

}
